//
//  MSBtnSelectorView.m
//  JYG_Agent
//
//  Created by apple on 15/10/21.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "MSBtnSelectorView.h"

@interface MSBtnSelectorView ()
@property UIButton *curBtn;
@end
@implementation MSBtnSelectorView

-(void)cleanSelected
{
    for (int i=0; i<self.btnTitles.count; i++)
    {
        UIButton* btn=(UIButton*)[self viewWithTag:(100+i)];
        btn.selected=NO;
        btn.backgroundColor=[UIColor whiteColor];
        btn.layer.borderColor=[UIColor lightGrayColor].CGColor;
    }
    self.curBtn=nil;
    self.selected=nil;
}

-(void)setBtnTitles:(NSArray *)btnTitles
{
    _btnTitles = [btnTitles copy];
    if (!self.font) {
        self.font = [UIFont fontWithName:@"STHeitiSC-Light" size:15];
    }
    float x = 15, y = 0, interval = 30;
    for (int i=0; i<btnTitles.count; i++) {
        CGSize size = [HDUtil getSizeWithText:btnTitles[i] font:self.font];
        CGFloat btnWidth = size.width+20;
        if (x+btnWidth+interval>APPFRAME.size.width) {
            x = 15;
            y = y + 30;
        }
        GXButton *btn = [GXButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(x, y, btnWidth, 20);
        btn.imageViewFrame = CGRectMake(0, btn.height/2.0-7.5, 15, 15);
        btn.titleLabelFrame = CGRectMake(20, 0, size.width, btn.height);
        btn.titleLabel.font = self.font;
        [btn setImage:[UIImage imageNamed:@"btnSelector_nor"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"btnSelector_pre"] forState:UIControlStateSelected];
        [btn setTitle:btnTitles[i] forState:UIControlStateNormal];
        [btn setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
        btn.relayout = YES;
        btn.tag = 100+i;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        x = x+btnWidth+interval;
    }
    self.frame = CGRectMake(0, 0, APPFRAME.size.width, y+30);
}

- (void)btnAction:(UIButton *)sender
{
    if (self.curBtn!=sender) {
        self.curBtn.selected = NO;
        self.curBtn = sender;
    }
    sender.selected = !sender.selected;
}

-(NSString*)selected
{
    NSString* str=nil;
    
    for (int i=0; i<self.btnTitles.count; i++)
    {
        UIButton* btn=(UIButton*)[self viewWithTag:(100+i)];
        if (btn.selected)
        {
            if (str==nil)
            {
                str=[NSString string];
            }
            else
            {
                str=[str stringByAppendingString:@","];
            }
            
            str=[str stringByAppendingString:btn.titleLabel.text];
        }
    }
    return str;
}

@end
